<?php
namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use common\helps;
use yii\helpers\ArrayHelper;

class CustMaster extends ActiveRecord{
    const USER_FLAG_YES	= 1;	//是否使用
    const USER_FLAG_NO	= 0;	//bu

	const USER_SOURCE_SHOP		= 1;
	const USER_SOURCE_GENER		= 2;
	//add by FDG367 491 【后台管理】会员查询页面，用户来源显示调整 start
	const USER_SOURCE_SHOP_WAP	= 3;//
	//add by FDG367 491 【后台管理】会员查询页面，用户来源显示调整 end

	const USER_SOURCE_TYPE_GENER	= '线下';	//注册者线下
	const USER_SOURCE_TYPE_SHOP		= '线上';	//注册者线下
	//add by FDG367 491 【后台管理】会员查询页面，用户来源显示调整 start
	const USER_SOURCE_TYPE_SHOP_WAP	= '线上wap';	//注册者线上wap
	//add by FDG367 491 【后台管理】会员查询页面，用户来源显示调整 end

	const USER_SEX_MAN			= 2;	//注册者线下
	const USER_SEX_WENMAN		= 1;	//注册者线下

	//add by FDG367 491 【后台管理】会员查询页面，用户来源显示调整 start//来源对应文字描述
	public static $userSourceArr=[
		1=>'商城注册PC',
		2=>'线下同步',
		3=>':商城WAP'
	];
	//add by FDG367 491 【后台管理】会员查询页面，用户来源显示调整 end

	public static function tableName(){
        return '{{%cust_master}}';
    }

	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [
			[['username','mobile','pwd','member_no','wx_openid','wx_scan_openid','wx_unionid','wx_nickname','wx_sex','x_province','wx_city','wx_country','wx_headimgurl','wx_privilege','memo','use_flg','email','creator','create_time','edit_time','sex','member_source','consum_amount','current_points','birthday','province_code','province_name','city_code','city_name','district_code','district_name','adddress','source','editor'], 'safe'],
		];
	}
    /**
     * @获取创建人
     */
    public function getCreator(){
        $userInfo = \common\helps\tools::getloginUserInfo();
        if($userInfo){
            $userName = $userInfo->userName;
        }else{
            $userName = '';
        }
        return $userName;
    }

	/**
	 * @param $mobile 注册检查手机号和验证码
	 * @param $code
	 * @return int
	 */
    public function checkMobile($mobile,$code){
		$redis = new helps\redisHelper();
		$c_code = $redis->getSmsCode($mobile);

		if($c_code!=$code){
			return false;
		}

		return true;
    }

	/**
	 * @param $mobile 通过手机号检查线上是否存在此账号
	 * @return bool/ture
	 */
    public function checkMobileIsRegister($mobile,$type=0){

		//如果存在$type 直接返回对象
		if($type){
			return self::getCustInfo($mobile);
		}
		//获取会员信息
		$result	= helps\redisHelper::getMastserMobileInfo($mobile); //线上会员

		if(!$result){
			return false;
		}
		return $result;
    }

	/**
	 * @param $mobile 通过手机号检查线下手机号是否注册
	 * return bool/$info
	 */
	public function checkIsGenerMobileRegister($mobile='',$wx_openid=''){

		//初始化值
		$soap	= new helps\Soap();
		$soap->mobile		= $mobile;
		$soap->wx_openid	= $wx_openid;

		//查询到就返回相对应的数据，查询不到就返回false
		$generInfo	= $soap->getMembers();

		//如果异常或者数据为空则返回false
		if( !$generInfo || 0 >=count($generInfo->data)){
			return false;
		}

		return $generInfo;
	}

    //用户名密码是否匹配
    public function checkUserPwd($mobile,$pwd){

		//通过手机号查询当前用户信息
        $result = ArrayHelper::toArray(self::getCustInfo($mobile));

        if(!empty($result)){
            $c_pwd = helps\tools::md5pwd($pwd);
            if($result['pwd'] == $c_pwd){
                return $result;
            }else{
                return 1006;
            }
        }
        return 1005;
    }

	/**
	 * @param $data 增加线下数据
	 * @return array/false
	 */
	public function addGenerCustMaster($data){
		$soap 	= new helps\Soap();
		$soap->load(ArrayHelper::toArray($data),'');
		if(!$soapRegisterInfo	= $soap->register()){
			return false;
		}
		//TODO 更新对应的会员号
		return $soapRegisterInfo;
	}


    //修改密码
    public function updatePwd($oldPwd,$pwd){
        $master_info = \common\helps\tools::getloginMasterInfo();
        if(!empty($master_info)){
            $old_pwd = helps\tools::md5pwd($oldPwd);
            $master_where = ['mobile'=>$master_info->mobile];
            $master = $this::find()->where($master_where)->select('pwd')->asArray()->one();
            if(!empty($master)){
                if($old_pwd == $master['pwd']){
                    $data['pwd'] = helps\tools::md5pwd($pwd);
                    $data['edit_time'] = date('Y-m-d H:i:s',time());

                    $ret = $this->updateAll($data,'mobile=:mobile',array(':mobile'=>$master_info->mobile));
                    if($ret){
                        return 200;
                    }else{
                        return 2088;
                    }
                }else{
                    return 2002;
                }
            }else{
                return 2003;
            }
        }
        return 2001;
    }

	/**
	 * @param $mobile	手机号
	 * @param $data	修改数据
	 * @return bool|int
	 */
	public function updateCustMaster($mobile,$data){

		//删除用户的缓存
		if(!helps\redisHelper::delMastserMobileInfo($mobile)){
			return false;
		}

		return  $this->updateAll($data,'mobile=:mobile',array(':mobile'=>$mobile));
	}

	/*
	 * @param 通过线下会员号获取手机号
	 * @param $memberNo 线下会员号
	 */
	public static function getMastertMobile($memberNo){
		return self::getCustInfo('',$memberNo);
	}


	/**
	 * @param $mobile
	 * @return array|null|ActiveRecord
	 */
	public static function getMastertMobileInfo($mobile){
		return self::getCustInfo($mobile);
	}

	/**
	 * @param 通过微信unionid 或者openid 查询相对应的会员数据
	 * @param $wx_unionid 	微信unionid
	 * @param $wxOpenid 	微信openid
	 * @return array|null|ActiveRecord
	 */
	public static function getMastertWechatInfo($wx_unionid,$wxOpenid=''){
		return self::getCustInfo('','',$wxOpenid,$wx_unionid);
	}


	/**
	 * @param 保存线下数据
	 */
	public  function saveGener($generInfo){

		$this->member_no		=  $generInfo->MemberNo;//;;
		$this->mobile			=  $generInfo->MemberTele;//$generInfo['data'][0]->MemberName;
		$this->username			=  $generInfo->MemberName;
		$this->current_points	=  $generInfo->CurrentPoints;
		$this->email			=  $generInfo->MemberEmail;
		$this->consum_amount	=  $generInfo->ConsumAmount;
		$this->wx_openid		=  $generInfo->WeiXinID;
		$this->sex				=  $generInfo->MemberSex=="男"?2:1;
		$this->province_code	=  '';
		$this->province_name	=  $generInfo->AddrProvince;
		$this->city_code		=  '';
		$this->city_name		=  $generInfo->AddrCity;
		$this->district_code	= 	'';
		$this->district_name	=  $generInfo->AddrDistrict;
		$this->adddress			=  $generInfo->AddrDesc;
		//mod by FDG367 20180115 个人中心/出生日期默认时间修改 448 start
		$this->birthday			=  $this->birthday?$this->birthday:'1980-01-01';
		//mod by FDG367 20180115 个人中心/出生日期默认时间修改 448 start
		$this->source			= !empty($this->source)?$this->source:self::USER_SOURCE_SHOP;
		//mod by FDG367 清除用户缓存 登录缓存数据和数据库数据不一致导致报错 458 start
		$this->wx_nickname		= empty($this->wx_nickname)?'':$this->wx_nickname;
		//mod by FDG367 清除用户缓存 登录缓存数据和数据库数据不一致导致报错 458 end

		if(!$this->save()){
			return false;
		}

		return true;
	}

	/**
	 * @param bool $insert
	 * @return bool
	 */
	public function beforeSave($insert){
		if($insert){//插入
			$this->create_time	=date('Y-m-d H:i:s');
			$this->use_flg			= self::USER_FLAG_YES;
			$this->creator			= self::USER_SOURCE_TYPE_GENER;
			$this->editor			= self::USER_SOURCE_TYPE_GENER;
			$this->source			= !empty($this->source)?$this->source:self::USER_SOURCE_SHOP;
			$this->sex				= !empty($this->sex)?$this->sex:self::USER_SEX_WENMAN;
		}
		$this->edit_time	=date('Y-m-d H:i:s');
		return parent::beforeSave($insert);
	}

	/**
	 * @param string $mobile //所有的取用户信息都要经过这个方法
	 * @param string $member_no
	 * @param string $wx_openid
	 * @param string $wx_unionid
	 * @return array|bool|null|ActiveRecord
	 */
	public static function getCustInfo($mobile='',$member_no='',$wx_openid='',$wx_unionid=''){
		$params = array_filter([
			'mobile'		=> $mobile,
			'member_no'		=> $member_no,
			'wx_openid'		=> $wx_openid,
			'wx_unionid'	=> $wx_unionid
		]);

		if(!$params){
			return false;
		}

		//使用条件
		$params['use_flg'] = self::USER_FLAG_YES;

		//修改取缓存
		return self::find()
			->where($params)
			->one();
	}
}